package cn.xu.bookstore.cart.servlet;



import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itcast.servlet.BaseServlet;
import cn.xu.bookstore.book.domain.Book;
import cn.xu.bookstore.book.service.BookService;
import cn.xu.bookstore.cart.domain.Cart;
import cn.xu.bookstore.cart.domain.CartItem;

public class CartServlet extends BaseServlet {
	
	private BookService bookService = new BookService();
	
	public String add(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		/*
		 * 从session的购物城并 根据表单的bid查询数据库并设置 count
		 */
		Cart cart = (Cart) request.getSession().getAttribute("cart");
		String bid = request.getParameter("bid");
		Integer count = Integer.valueOf(request.getParameter("count"));
		Book book = bookService.load(bid);
		/*
		 * 创建购物车条目将该商品添加到 购物条目中
		 */
		CartItem cartItem = new CartItem();
		cartItem.setBook(book);
		cartItem.setCount(count);
		cart.add(cartItem);
	
		return "f:/jsps/cart/list.jsp";
	}
	
	public String clear(HttpServletRequest request, HttpServletResponse response){
		Cart cart = (Cart)request.getSession().getAttribute("cart");
		cart.clear();
		
		return "f:/jsps/cart/list.jsp";
	}
	
	/*
	 * 删除指定条目
	 */
	public String delete(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Cart cart = (Cart)request.getSession().getAttribute("cart");
		String bid = request.getParameter("bid");
		cart.remove(bid);
		
		return "f:/jsps/cart/list.jsp";
	}
	
	

}
